#include <iostream>
#include <signal.h>

void PrintPending(sigset_t pending)
{
    std::cout << "current process [" << getpid() << "] pending: ";
    for (size_t i = 31; i >= 1; i--) // 信号31~1 == 位图下标
    {
        if (sigismember(&pending, i))
        {
            std::cout << 1;
        }
        else
        {
            std::cout << 0;
        }
    }
    std::cout << std::endl;
}

void handler(int signal)
{
    std::cout << "信号 " << signal << " 被递达" << signal << std::endl;
    std::cout << "-------------------------------------------" << std::endl;
    sigset_t pending;
    sigpending(&pending);
    PrintPending(pending);
    std::cout << "-------------------------------------------" << std::endl;
}

int main()
{
    // 0.捕捉信号2
    signal(SIGINT, handler);
    // signal(SIGINT, SIG_IGN);//忽略信号
    // signal(SIGINT, SIG_DFL);//执行对应的默认行为

    // 1.屏蔽SIGINT 2 ---修改block表
    sigset_t block_set, old_set;
    sigemptyset(&block_set); // 初始化
    sigemptyset(&old_set);
    sigaddset(&block_set, SIGINT);
    // 1.1设置进程block表
    sigprocmask(SIG_BLOCK, &block_set, &old_set);

    int cnt = 10;
    while (true)
    {
        // 2.获取当前信号的pending信号集
        sigset_t pending;
        sigpending(&pending);
        // 3.打印pending信号集
        PrintPending(pending);
        // 4.解除对 SIGINT 2 的屏蔽
        if (cnt == 0)
            sigprocmask(SIG_SETMASK, &old_set, &block_set);

        cnt--;
        sleep(1);
    }

    return 0;
}